package bill.study.algorithms.arraysStrings;

import java.util.Arrays;
import java.util.Comparator;
import java.util.HashSet;

public class SortStrWithAnagrams {
	
	static public void main(String [] args){
		/** please note the result depends on where "simon" appears!!! */
		String [] s = new String[] {"dog",  "bill", "simon", "simple","god", "smplei"};
		printarr(s);
		sortWithAnagrams(s);
		printarr(s);
	}

	static  <E> void printarr(E [] arr){
		System.out.println("-----------------------------------------");
		for(int i = 0; i < arr.length; i ++){
			System.out.println(arr[i]);
		}
	}
	static void sortWithAnagrams(String[] arr) {
		Arrays.sort(arr, new Comparator<String>() {
			public int compare(String s1, String s2) {
				if (isAnagram(s1, s2)) {
					return 0;
				}
				return s1.compareTo(s2);
			}
		});
	}

	static boolean isAnagram(String s1, String s2) {
		HashSet<Character> set1 = new HashSet<Character>();
		for (int i = 0; i < s1.length(); i++) {
			set1.add(s1.charAt(i));
		}

		HashSet<Character> set2 = new HashSet<Character>();
		for (int i = 0; i < s2.length(); i++) {
			set2.add(s2.charAt(i));
		}

		return set1.equals(set2);

	}
	
	static boolean isAnagram2(String s1, String s2) {
		HashSet<Character> set1 = new HashSet<Character>();
		/**
		 * The following does not compile, why not?
		 * Because char is not an object. the whole array is treated as an object.
		 */
		set1.addAll(Arrays.asList(s1.toCharArray()));
		
		Character [] charArr = new Character [100];
		
		/**
		 * But this one compiles, can you figure out why?
		 * because Character is object
		 * This is a good puzzle for Joshua Bloch
		 */
		set1.addAll(Arrays.asList(charArr));

		HashSet<Character> set2 = new HashSet<Character>();
		for (int i = 0; i < s2.length(); i++) {
			set2.add(s2.charAt(i));
		}

		return set1.equals(set2);

	}
}
